package main

import (

    "fmt"
    "flag"
    "net/url"
    "os"
)

var (
    h bool
    v bool

    ipp string
    us string
    pa string
    vminfo_fname string
    s1 string
    s2 string
)

type VmData struct {

    nodeip string
    node string
    vmid string
    vmp []string
    vmp_num int
}

var vm_file_path1 string = "c:\\chnet-s1-ec.bat"
var vm_file_path2 string = "c:\\chnet-s2.bat"
var logfile = "output.log"
var f *os.File

func usage() {
    fmt.Println("vm-netch-robot version: vm-netch-robot/1.0.0")
    fmt.Println("Usage: vm-netch-robot [-h 帮助] [-v 版本号] [-u 用户名] [-p 密码] [-c 执行文件]")
    flag.PrintDefaults()
}

func init() {
    flag.BoolVar(&h, "h", false, "显示帮助")
    // 另一种绑定方式
    flag.BoolVar(&v, "v", false, "显示版本号")

    flag.StringVar(&ipp, "i", "192.168.115.12", "需要操作的服务器ip")
    flag.StringVar(&us, "u", "root@pam", "获取ticket所需要的用户名")
    flag.StringVar(&pa, "p", "nicaiba_88", "获取ticket所需要的密码")
    flag.StringVar(&vminfo_fname, "c", "vmInfo.txt", "需要修改的虚拟机信息文件")
    flag.StringVar(&s1, "s1", "chnet-s1-ec.bat", "第一个需要传的脚本")
    flag.StringVar(&s2, "s2", "chnet-s2.bat", "第二个需要传的脚本")
    flag.Usage = usage
}

func checkFileIsExist(filename string) bool {
    var exist = true
    if _, err := os.Stat(filename); os.IsNotExist(err) {
        exist = false
    }
    return exist
}

/*发送json格式数据*/
func main() {

    flag.Parse()
    if h {
        flag.Usage()
        return
    }

    if v {
        fmt.Println("vm-netch-robot version: vm-netch-robot/1.0.0")
        return 
    }

    // flag.Args() 函数返回没有被解析的命令行参数
    // func NArg() 函数返回没有被解析的命令行参数的个数
    // fmt.Printf("args=%s, num=%d\n", flag.Args(), flag.NArg())
    // for i := 0; i != flag.NArg(); i++ {
    //     fmt.Printf("arg[%d]=%s\n", i, flag.Arg(i))
    // }
    
    if checkFileIsExist(logfile) {
        
        fmt.Println("文件存在, 删除")
        os.Remove(logfile)
    }
    fp, err := os.OpenFile(logfile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    f = fp

    var ip string
    var username string
    var passwd string
    ip = ipp
    username = us
    passwd = pa

    url_ticket := "https://" + ip + ":8006/api2/json/access/ticket"
    postdata_ticket := "username=" + username + "&password=" + passwd

    fmt.Println("url:" + url_ticket)
    fmt.Println("postdata:" + postdata_ticket)

    ret_get := get_ticket(url_ticket, "username=root@pam&password=nicaiba_88")
    if ret_get == -1 {
        fmt.Println("get ticket error")
        return
    }
    
    ret_parse := parse_ticket()
    if ret_parse == -1 {
        fmt.Println("parse ticket error")
        return
    }

    var context1 string = read_file(s1)
    var context2 string = read_file(s2)

    vmdata := read_info(vminfo_fname)  

    fmt.Printf("虚拟机数量=%d\n\n", len(vmdata))

    for _, one := range vmdata {

        //fmt.Printf("节点名称=%s, 节点ip=%s, vmid=%s, vmip=%s, vmgw=%s\n", 
        //    one.node, one.nodeip, one.vmid, one.vmip, one.vmgw)
        // record := fmt.Sprintf("节点名称=%s, 节点ip=%s, vmid=%s, vmip=%s, vmgw=%s\n", 
        //     one.node, one.nodeip, one.vmid, one.vmip, one.vmgw)
        // _, errw := f.Write([]byte(record)) 
        // if errw != nil {
        //     fmt.Println(errw.Error())
        // }

        url_wfile := "https://" + one.nodeip + ":8006/api2/json/nodes/" + one.node + "/qemu/" + one.vmid + "/agent/file-write"
        postdata_wfile1 := "content=" + url.QueryEscape(context1) + "&file=" + vm_file_path1

        fmt.Printf("节点名称=%s, 节点ip=%s, vmid=%s, 参数个数:%d\n", one.node, one.nodeip, one.vmid, one.vmp_num)
		for i := 0; i < one.vmp_num; i++ {
            fmt.Printf("%s ", one.vmp[i])
            context2 = context2 + " " + one.vmp[i]
        }
        fmt.Printf("\n\n");
        
        postdata_wfile2 := "content=" + context2 + "&file=" + vm_file_path2

        //fmt.Printf("%s\n", url_wfile)
        //fmt.Printf("%s\n", context1)
        //fmt.Printf("%s\n", context2)

        ret_wfile1 := post(url_wfile, postdata_wfile1)
        if ret_wfile1 == -1 {
            fmt.Println("write file1 error")
            return
        }

        ret_wfile2 := post(url_wfile, postdata_wfile2)
        if ret_wfile2 == -1 {
            fmt.Println("write file2 error")
            return
        }

        url_efile := "https://" + one.nodeip + ":8006/api2/json/nodes/" + one.node + "/qemu/" + one.vmid + "/agent/exec"
        postdata_efile := "command=" + vm_file_path2
        ret_efile := post(url_efile, postdata_efile)
        if ret_efile == -1 {
            fmt.Println("exec file error")
            return
        }

    }
    f.Close()
}